<?php

namespace app\http\middleware;

use thans\jwt\exception\JWTException;
use thans\jwt\facade\JWTAuth;

class ApiLoginCheck
{
    public function handle($request, \Closure $next)
    {
        try {
            $payLoad = JWTAuth::getPayload();
            if (empty($payLoad['uid'])) {
                return json(['code' => -1, 'msg' => '请重新登录']);
            } else {
                $jwtArray = [];
                foreach($payLoad as $val){
                    $jwtArray[$val->getName()] = $val->getValue();
                }
                $token = JWTAuth::getToken();
                $jwtArray['token'] = $token;
                $request->jwt = $jwtArray;
            }
            JWTAuth::auth();
            // 判断用户账号是否可用jwtArray中的uid是用户ID

            return $next($request);

        } catch (JWTException $e) {
            return json(['code' => -1, 'msg' => '请重新登录']);
        }
    }
}
